import { message } from '@/components/basic/message';
import { ResultEnum } from '@/enums/httpEnum';
import router from '@/router';
import { useUserStore } from '@/store/modules/user';
import axios from 'axios';
import type { AxiosInstance, AxiosResponse, CancelTokenStatic } from 'axios';
import { ElMessageBox } from 'element-plus';

/** 真实请求的路径前缀 */
export const baseApiUrl = import.meta.env.VITE_BASE_API_URL;

const controller = new AbortController();
const service: AxiosInstance & { CancelToken?: CancelTokenStatic } = axios.create({
  baseURL: baseApiUrl,
  // adapter: 'fetch',
  timeout: 10000,
  signal: controller.signal
});

service.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    const token = userStore.token;
    if (token && config.headers) {
      // 请求头token信息，请根据实际情况进行修改
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => {
    Promise.reject(error);
  }
);

const UNKNOWN_ERROR = '未知错误，请重试';

service.interceptors.response.use(
  (response: AxiosResponse<BaseResponse>) => {
    const res = response.data;
    // if the custom code is not 200, it is judged as an error.
    if (res.code !== ResultEnum.SUCCESS && res.code !== ResultEnum.SUCCESS_2_CODE) {
      message.error(res.message || UNKNOWN_ERROR);
      // Illegal token
      if ([401].includes(res.code)) {
        // to re-login
        ElMessageBox.confirm(res.message || '账号异常，您可以取消停留在该页上，或重新登录', 'Warning', {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          localStorage.clear();
          window.location.reload();
        });
      }

      // throw other
      const error = new Error(res.message || UNKNOWN_ERROR) as Error & {
        code: any;
      };
      error.code = res.code;
      return Promise.reject(error);
    } else {
      // const sseStore = useSSEStore();
      // sseStore.setServerConnectStatus(true);

      return response;
    }
  },
  error => {
    if (error.response && error.response.status === 401) {
      console.error('Token过期，请重新登录！');

      localStorage.clear();
      window.location.reload();
    } else {
      console.error('请求错误，请稍后再试！');
    }

    return Promise.reject(error); // 仅针对带有响应状态的错误拒绝 Promise
  }
);

type BaseResponse<T = any> = Omit<API.ResOp, 'data'> & {
  data: T;
};

service.CancelToken = axios.CancelToken;

export default service;
